/**
 * 科大讯飞 通用文字识别
 * https://www.xfyun.cn/doc/words/universal_character_recognition/API.html
 * */


const fs = require('fs');
const path = require('path');
const CryptoJS = require("crypto-js/crypto-js");
const colors = require('colors');
const HTTP = require('../../service/index');
const config = require('./config');
const { API_KEY, API_SECRET, getURCOutput } = require('../../config/index');


const BASE_URL = 'https://api.xf-yun.com';
const HOST = 'api.xf-yun.com'

const POST_URL = '/v1/private/sf8e6aca1'

/**
 * 获取鉴权参数
 * @returns
 */
function getAuthorization() {
  const date = new Date().toUTCString()

  const signature_origin = `host: ${HOST}\ndate: ${date}\nPOST ${POST_URL} HTTP/1.1`;
  const signature_sha = CryptoJS.HmacSHA256(signature_origin, API_SECRET);
  const signature = CryptoJS.enc.Base64.stringify(signature_sha);

  const authorization_origin = `api_key="${API_KEY}",algorithm="hmac-sha256",headers="host date request-line",signature="${signature}"`
  return `?authorization=${CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(authorization_origin))}&host=${HOST}&date=${date}`
}

/**
 * 获取待提取图片的文件名、后缀名、base64数据
 * @returns
 */
function imageParasm(imgPath) {
  if (!imgPath) {
    return new Error('图片地址为空')
  }
  const imgBuf = fs.readFileSync(imgPath)
  const extname = path.extname(imgPath).split('.')[1]
  const fileName = path.basename(imgPath, `.${extname}`)
  return {
    extname,
    fileName,
    imgBase64: imgBuf.toString('base64')
  }
}


function initChange(imgPath) {
  const authorization = getAuthorization();
  const { imgBase64, extname, fileName } = imageParasm(imgPath)
  const fileAllName = `${fileName}.${extname}`
  HTTP.post(BASE_URL + POST_URL + authorization, config.getPostParmas(extname, imgBase64))
    .then(res => {
      if (res.data) {
        const data = res.data;
        if (data.header.code === 0) {
          const textObj = CryptoJS.enc.Base64.parse(data.payload.result.text).toString(CryptoJS.enc.Utf8);
          const txt = formatTextHanler(JSON.parse(textObj))
          console.log(fileAllName + '----提取成功'.brightGreen)
          writeFiles(txt, fileName)
        }
      }

    })
    .catch(err => {
      console.log(fileAllName + '----提取失败'.brightRed, err)
      // console.log('beginChange err', err)
      // console.log('beginChange err status', err.response.status)
      // console.log('beginChange err data', err.response.data)
    })
}

/**
 * 将文本对象转为普通文本
 * @param {*} textObj
 * @returns
 */
function formatTextHanler(textObj) {
  let result = ``
  textObj.pages.forEach(page => {
    page.lines.forEach(line => {
      if (line.exception === -1) {
        return
      }
      // console.log('coord', line.coord)
      result += '\n'
      if (line.words && line.words.length) {
        line.words.forEach(word => {
          result += word.content + ' ';
        })
      }
    })
  })
  return result;
}

/**
 * 将文本写入文件内
 * @param {*} txtStr
 */
function writeFiles(txtStr, fileName) {
  // 翻译繁体字
  fs.writeFileSync(getURCOutput() + fileName + '.txt', txtStr)
}

function init() {
  const sourceFiles = config.readSourceSync();
  if (!sourceFiles || !sourceFiles.length) {
    console.log('暂无可提取的文件,请检查目录'.brightRed)
    return
  }
  sourceFiles.forEach(fileUrl => {
    initChange(fileUrl)
  })
}

init();